/**
 *
 */
var ExternalSource = {
	labelRE:/label/i,
	className:"active",
	init:function(id){
		var target = $(id);
		target.observe("click",ExternalSource.tabEvent);
		var es = target.up(".externalSourceElement");
		var as = es.getElementsByTagName("a");
		var anchor = as[as.length - 1];
		es.appendChild(anchor);
		anchor.clonePosition(es);
		document.getElementsByTagName("body")[0].appendChild(target);
		target.absolutize();
		target.clonePosition(es,{setHeight:false});
	},
	tabEvent:function(event){
		ExternalSource.tabControl(event.element())
	},
	tabControl:function(target){
		var ancestor = null;
		var isLabel = ExternalSource.labelRE.test(target.nodeName)
		if (isLabel && target.up) {
			var ancestor = target.up(".t-beaneditor-row");
			if ( ancestor != null ) {
				ancestor.adjacent(".t-beaneditor-row").each(function(el){
					el.removeClassName(ExternalSource.className);
				});
				ancestor.addClassName(ExternalSource.className);
			}
		}
	}
};

/**
 * Registering with LinkListener to enable the first tab when the editor gets opened.
 * This was originally part of the init process, but for reasons beyond me in IE7 the
 * prototype lib hasn't fully been initialized and caused errors.
 * Also, IE7 doesn't support the :target pseudo-class :(
 */
LinkListener.addHandler("externalSourceEditor", function(link) {
	var id = link.href.substr(link.href.indexOf("#") + 1);
	ExternalSource.tabControl($(id).getElementsByTagName("label")[0]);
	if (document.all) { //IEx cheapshot targetting
		$(id).addClassName("target");
	}
	$(id).up().addClassName("focus");
	return false;//Only need to enable the first tab, the rest is up to the browser
});

/**
 * A helper function, because in T5 this is the easiest way to add an init method.
 * If I use my own init method I try to instantiate before Prototype is finished
 * initializing, let's see if this solves that problem...
 */
function createNewExternalSource(targetId) {
	ExternalSource.init(targetId);
}
//Checking for existance and then adding it to Tapestry's structure, trying to minimize the dependencies for this code...
if (Tapestry && Tapestry.Initializer) Tapestry.Initializer["createNewExternalSource"] = createNewExternalSource;
